package com.aaa.data;

import com.aaa.config.SSLHelper;
import com.aaa.dto.BookCatalogueDto;
import com.aaa.service.BookService;
import com.aaa.service.impl.BookServiceImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

import static com.aaa.util.DataProcessing.splitList;

/**
 * @author 杨森
 * @version 1.0
 * @Title:
 * @date 2020/8/10 15:16
 */
public class DownloadBook {
    private static final int count=3;
    public static void setDataSource(String bookCod, String bookName, String dataSource,
                                     HttpServletRequest request, BookServiceImpl bookService,ExecutorService executorService) {
        SSLHelper.init();
        switch (dataSource){
            case "biquge5200" :
                biquge5200(bookCod, bookName, dataSource, bookService, executorService);
            case "biquge" :
                biquge(bookCod, bookName, dataSource, bookService, executorService);
            case "ddxs" :
                ddxs(bookCod,bookName,dataSource,bookService, executorService);
        }
    }

    private static void ddxs(String bookCod, String bookName, String dataSource, BookServiceImpl bookService, ExecutorService executorService) {
        try {
            List<BookCatalogueDto> bookCatalogueDto = bookService.getBookCatalogue(bookCod, dataSource);
            Map<Integer, List<BookCatalogueDto>> integerListMap = splitList(bookCatalogueDto, count);
            CountDownLatch latch = new CountDownLatch(count);
            for (int i = 0; i < count; i++) {
                final int ins = i + 1;
                executorService.execute(() -> {
                    try {
                        ddxsGet(bookCod, bookName + ins, integerListMap.get(ins-1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            //合并文件
            combine(bookName);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

    private static void ddxsGet(String bookCod, String bookName, List<BookCatalogueDto> bookCatalogueDto) {
        try {
            String path = "/usr/local/webapps/file/" + bookName + ".txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                return;
            }

            //创建一个输出流,将爬到的小说以txt形式保存在硬盘
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            bookCatalogueDto.forEach(e -> {
                System.out.println(e.getCatalogueName() + "正在下载中。。。。" + Thread.currentThread().getName());
                Document document = null;
                try {
                    document = Jsoup.connect("http://www.ddxs.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                } catch (Exception exception) {
                    try {
                        Thread.sleep(4000);
                        try {
                            document = Jsoup.connect("http://www.ddxs.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                        } catch (Exception exception1) {
                            exception1.printStackTrace();
                            return;
                        }
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                }
                try {
                    bw.write(e.getCatalogueName());
                    bw.newLine();
                    bw.flush();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                Elements elements = document.select("#contents");
                String replace = elements.get(0).html().replace("<script>show_htm2();</script> ", "").replace("<script>show_htm3();</script>", "");
                try {
                    String[] split = replace.replace("<p>", "").split("</p>");
                    for (String s : split) {
                        bw.write(s);
                        bw.newLine();
                        bw.flush();
                    }

                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void biquge(String bookCod, String bookName, String dataSource, BookServiceImpl bookService, ExecutorService executorService) {
        try {
            List<BookCatalogueDto> bookCatalogueDto = bookService.getBookCatalogue(bookCod, dataSource);
            Map<Integer, List<BookCatalogueDto>> integerListMap = splitList(bookCatalogueDto, count);
            long start = System.currentTimeMillis();
            CountDownLatch latch=new CountDownLatch(count);
            for (int i = 0; i < count; i++) {
                final int ins=i+1;
                executorService.execute(() -> {
                    try {
                        biqugeGet(bookCod, bookName + ins, integerListMap.get(ins-1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            //合并文件
            combine(bookName);
            long end = System.currentTimeMillis();
            System.out.println("本次下载共用时"+(end-start));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

    private static void biquge5200(String bookCod, String bookName, String dataSource, BookServiceImpl bookService, ExecutorService executorService) {
        try {
            String path = "/usr/local/webapps/file/" + bookName + ".txt";
            File file = new File(path);
            if (file.exists()) {
                return;
            }
            List<BookCatalogueDto> bookCatalogueDto = bookService.getBookCatalogue(bookCod, dataSource);
            Map<Integer, List<BookCatalogueDto>> integerListMap = splitList(bookCatalogueDto, count);
            long start = System.currentTimeMillis();
            CountDownLatch latch=new CountDownLatch(count);
            for (int i = 0; i < count; i++) {
                final int ins=i+1;
                executorService.execute(() -> {
                    try {
                        biquge5200Get(bookCod, bookName + ins, integerListMap.get(ins-1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            //合并文件
            combine(bookName);
            long end = System.currentTimeMillis();
            System.out.println("本次下载共用时"+(end-start));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

    public static void biquge5200Get(String bookCod, String bookName, List<BookCatalogueDto> bookCatalogueDto) throws
            Exception {
        String path = "/usr/local/webapps/file/" + bookName + ".txt";
        File file = new File(path);
        //创建一个输出流,将爬到的小说以txt形式保存在硬盘
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        try {

            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                return;
            }
            bookCatalogueDto.forEach(e -> {
                System.out.println(e.getCatalogueName() + "正在下载中。。。。" + Thread.currentThread().getName());
                Document document = null;
                try {
                    document = Jsoup.connect("https://www.biquge5200.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                } catch (IOException ioException) {
                    try {
                        Thread.sleep(4000);
                        try {
                            document = Jsoup.connect("https://www.biquge5200.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                        } catch (IOException exception) {
                            return;
                        }
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                }
                try {
                    bw.write(e.getCatalogueName());
                    bw.newLine();
                    bw.flush();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                Elements elements = document.select("#content");
                String html = elements.get(0).html().replace("<div id='content'>", "").replace("</div>", "");
                String replace = html.replace("<script>readx();</script>", "").replace("<script>chaptererror();</script>", "");
                try {
                    String[] split = replace.replace("<p>", "").split("</p>");
                    for (String s : split) {
                        bw.write(s);
                        bw.newLine();
                        bw.flush();
                    }

                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });
        }catch (Exception e){
            bw.close();
            e.printStackTrace();
        }
    }

    private static void biqugeGet(String bookCod, String bookName,List<BookCatalogueDto> bookCatalogueDto) throws FileNotFoundException {
        try {
            String path = "/usr/local/webapps/file/" + bookName + ".txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                return;
            }
            //创建一个输出流,将爬到的小说以txt形式保存在硬盘
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            bookCatalogueDto.forEach(e -> {
                System.out.println(e.getCatalogueName() + "正在下载中。。。。");
                Document document = null;
                try {
                    document = Jsoup.connect("https://www.biquge.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                } catch (Exception e1) {
                    try {
                        Thread.sleep(4000);
                        document = Jsoup.connect("https://www.biquge.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }
                try {
                    bw.write(e.getCatalogueName());
                    bw.newLine();
                    bw.flush();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                Elements elements = document.select("#content");
                String html = elements.get(0).html().replace("<div id='content'>", "").replace("</div>", "");
                String replace = html.replace("<script>readx();</script>", "").replace("<script>chaptererror();</script>", "");
                try {
                    String[] split = replace.split("<br>");
                    for (String s : split) {
                        bw.write(s);
                        bw.newLine();
                        bw.flush();
                    }

                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void combine(String bookName) throws Exception {
        String bookPath = "/usr/local/webapps/file/" + bookName + ".txt";
        File file = new File(bookPath);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        for (int i = 1; i < 4; i++) {
            String path = "/usr/local/webapps/file/" + bookName + i + ".txt";
            File file1 = new File(path);
            if (file1.exists()) {
                BufferedReader br = new BufferedReader(new FileReader(file1));
                String line;
                while (true) {
                    if ((line = br.readLine()) == null) {
                        br.close();
                        break;
                    }
                    bw.write(line);
                    bw.newLine();
                }
            }
            file1.delete();
        }
        bw.flush();
        bw.close();
    }
}
